package com.faxsun.web.processor;


import javax.ws.rs.core.Response;

import org.broadleafcommerce.core.web.api.BroadleafWebServicesException;
import org.springside.modules.utils.PropertiesLoader;

import com.faxsun.api.endpoint.common.CommonEndpointConstants;
import com.faxsun.controller.uc.entity.AssistTool;

public class RestfulProcessor{
	protected static PropertiesLoader propertiesLoader = new PropertiesLoader("classpath:/restful.properties");

	public static void authenticationCheck(String keys) {
		int result = check(keys);
		if (result == -1) {
			throw BroadleafWebServicesException.build(
					Response.Status.UNAUTHORIZED.getStatusCode()).addMessage(
					CommonEndpointConstants.KEY_FORMAT_ERROR);
		} else if (result == -2) {
			throw BroadleafWebServicesException.build(
					Response.Status.UNAUTHORIZED.getStatusCode()).addMessage(
					CommonEndpointConstants.TIMEOUT_ERROR);
		} else if (result == -3) {
			throw BroadleafWebServicesException.build(
					Response.Status.UNAUTHORIZED.getStatusCode()).addMessage(
					CommonEndpointConstants.AUTHENTICATION_FAIL);
		}
	}

	/*
	 * -1 : checked string format error. [uuid+nonce+timeStramp+api_sig] 
	 * -2 :	time out.
	 * -3 : authentication fail.
	 */
	private static int check(String str){
		if(str != null && !str.isEmpty()){			
			String[ ] afterSplit= new String[4]; 
			String uuid;
			String nonce;
			String time;
			String api_sig;
			try{
				afterSplit=str.split("\\+");
				uuid = afterSplit[0];
				nonce = afterSplit[1];
				time = afterSplit[2];
				api_sig = afterSplit[3];
			}catch (Exception e){
				return -1;
			}
			
			if(uuid == null || uuid.isEmpty() || nonce ==null || nonce.isEmpty() || time == null 
					|| time.isEmpty() || api_sig == null || api_sig.isEmpty()) {
				return -1;
			}
			
			/***
			 *
			SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss"); 						
			Date date;
			try {
				date = sdf.parse(time);
				if(AssistTool.timeoutCheck(date, 60)){
					return -2;
				}
			} catch (ParseException e) {
				e.printStackTrace();
				return -2;
			}	
			 *						
			*/
			
			String api_key = propertiesLoader.getProperty("api_key");
			String api_secret = propertiesLoader.getProperty("api_secret");
			String sig = AssistTool.getApi_sigMD5(api_key, nonce, time, uuid, api_secret);
			if(sig.equals(api_sig)){
				return 0;
			}else{
				return -3;
			}
		}
			
		return -1;	
	}
}

